package hw.ats.news.activity.cmt;

import hw.ats.news.R;
import hw.ats.news.model.Cmt;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.util.App;
import hw.ats.news.util.DataLoader;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.humanwares.ui.tabbar.TabHost;
import com.humanwares.util.DateUtil;
import com.humanwares.util.HwUtil;
import com.tattermedia.allthataudio.audio.AudioPlayerManager;
import com.tattermedia.allthataudio.audio.CommonAudioPlayerStatusListener;
import com.tattermedia.allthataudio.audio.IAudioPlayerStatusListener;
import com.tattermedia.allthataudio.misc.DebugFlag;
import com.tattermedia.allthataudio.views.AudioPlayerProgressView;

public class CmtAct extends Activity {
	@SuppressWarnings("unused")
	private static final String TAG = "CmtAct";
	
	private TabHost navbar = null;
	private ListView cmtListView = null;
	private List<Cmt> items = new ArrayList<Cmt>();
	
	private int newsUid = 0;
	
	// 페이징
	private int start = 0;
	private int rows = App.ROW_PER_PAGE;
	private boolean hasNext = true;
	private float density = 1.5f;
	
	// audio status listener
	private IAudioPlayerStatusListener		mAudioStatusListener;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.act_cmt);
        
        density = getResources().getDisplayMetrics().density;
        
        // 탭바 초기화
        navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB5);
		navbar.setVisibility(View.INVISIBLE); //TODO:에니메이션을 사용해서 숨겨지는 게 보이도록 처리
		
		// 네비게이션바 제목
        CommonUI.renderAppTitle(this);
        
        // 좌측 네비게이션 버튼 = 검색화면이동
        CommonUI.addLeftNavigationButtonBackEvent(this);
        
        Intent intent = getIntent();
        newsUid = intent.getIntExtra(App.INTENT_EXTRA_NEWS_UID, 0);
        if (newsUid <= 0) {
        	Toast.makeText(this, "댓글 정보를 조회할 수 없습니다.", Toast.LENGTH_SHORT).show();
        	finish();
        }
        
        // 댓글 쓰기
		ImageButton cmtAddBtn = (ImageButton)findViewById(R.id.cmt_add_btn);
		cmtAddBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(CmtAct.this, CmtAddAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, newsUid);
				intent.putExtra(App.INTENT_EXTRA_ACT_NAME, CmtAddAct.class.getName());
				CmtAct.this.startActivityForResult(intent, 1000);
			}
		});
		
		cmtListView = (ListView)findViewById(R.id.cmt_list);
		cmtListView.setAdapter(new CmtAdapter(CmtAct.this));
		
    	int networkType = HwUtil.connectivityType(this);
    	if (networkType == -1) {
    		Toast.makeText(this, 
    				"댓글을 수신할 수 없습니다.\n네트워크 접속 상태를 확인하여 주십시오.", 
    				Toast.LENGTH_SHORT).show();
    		return;
    	}
    	
    	   // add audio status listener
        mAudioStatusListener = new CommonAudioPlayerStatusListener(
        		(ImageButton)findViewById(R.id.audio_player_button_play), 
        		(ImageButton)findViewById(R.id.audio_player_button_repeat),
        		(ImageButton)findViewById(R.id.audio_player_button_prev),
        		(ImageButton)findViewById(R.id.audio_player_button_next),
        		(TextView)findViewById(R.id.audio_player_text_subject),
        		(TextView)findViewById(R.id.audio_player_text_time),
        		(AudioPlayerProgressView)findViewById(R.id.audio_player_progress_view));
        
        AudioPlayerManager.getManager().addAudioPlayerStatusListener(mAudioStatusListener);
    	

		loadData();
		
		setResult(1000, getIntent());
    }
    
    @Override
    protected void onDestroy() {
    	
    	AudioPlayerManager.getManager().removeAudioPlayerStatusListener(mAudioStatusListener);
    	
    	super.onDestroy();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        int visibility = navbar.getVisibility();
        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
        return false;
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != 1000)
			return;
		
		// 댓글 추가
		if (requestCode == 1000) {
			refreshData();
		}
		
		// 댓글 변경
		else if (requestCode == 2000) {
			refreshData();
		}
		
		// 댓글 서브 댓글 추가
		else if (requestCode == 3000) {
			refreshData();
		}
	}
    
    private void refreshData() {
    	items.clear();
    	loadData();
    }

	private void loadData() {
       	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    	    	progressDialog = ProgressDialog.show(
    	    			CmtAct.this, App.APP_TITLE, "글을 수신하고 있습니다.", true, false);
    		}
    		
			@Override
			protected Boolean doInBackground(String... params) {
				List<Cmt> newItems = DataLoader.loadCmtList(newsUid, start, rows + 1);
				if (newItems != null && newItems.size() == rows + 1) {
					newItems.remove(rows);
					hasNext = true;
				} else {
					hasNext = false;
				}

				if (newItems != null && newItems.size() > 0) {
					items.addAll(newItems);
				}

				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {

			}

			@Override
			protected void onPostExecute(Boolean result) {
				((BaseAdapter)cmtListView.getAdapter()).notifyDataSetChanged();
				progressDialog.dismiss();
				if (result == false) {
					Toast.makeText(CmtAct.this, "최신 글을 수신할 수 없습니다.\n네트워크 접속 상태를 확인하여 주십시오.", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
    }
    
//    /**
//     * 댓글 등록 결과
//     */
//    private final static int HANDLER_MSG_FOR_ADD = 0;
//    
//    /**
//     * 댓글 변경 결과
//     */
//    private final static int HANDLER_MSG_FOR_MOD = 1;
//    
//    /**
//     * 댓글의 댓글 결과
//     */
//    private final static int HANDLER_MSG_FOR_REPLY = 2;
    
    /**
     * 댓글의 삭제 결과
     */
    private final static int HANDLER_MSG_FOR_DEL = 3;
    
    private ProgressDialog progressDialog;
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
//        	// 등록처리
//        	if (msg.what == HANDLER_MSG_FOR_ADD) {
//        	}
//        	
//        	// 변경처리
//        	else if (msg.what == HANDLER_MSG_FOR_MOD) {
//        	}
//        	
//        	// 댓글의 댓글처리
//        	else if (msg.what == HANDLER_MSG_FOR_REPLY) {
//        	}
//        	
//        	// 삭제처리
//        	else
        	if (msg.what == HANDLER_MSG_FOR_DEL) {
        		refreshData();
        	}
        	
            progressDialog.dismiss();
        }
    };
    
	/**
	 * 댓글 목록 데이터 어뎁터
	 * @author pcraft
	 */
    private class CmtAdapter extends BaseAdapter {
    	private static final String TAG = "CmtAdapter";
    	private final Activity context;

        public CmtAdapter(Activity context) {
        	this.context = context;
        }

        public int getCount() {
        	if (items == null || items.size() == 0)
        		return 0;
        	
            return items.size() + (hasNext ? 1 : 0);
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            CmtHolder holder = null;
            
            // 페이징
            if (items.size() == position) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_more_article, null);
            	ImageButton btn = (ImageButton)view.findViewById(R.id.row_more_btn);
            	btn.setOnClickListener(new OnClickListener() {
        			@Override
        			public void onClick(View v) {
        				start += App.ROW_PER_PAGE;
        				loadData();
        			}
        		});
            	return view;
            }
            
            if (view == null || view.getTag() == null) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_cmt, null);
                holder = new CmtHolder(view);
                view.setTag(holder);
            } else {
            	holder = (CmtHolder)view.getTag();
            }

            final Cmt entry = items.get(position);
    		if (entry == null) {
    			return view;
    		}
    		
            if (holder.authorView != null)
            	holder.authorView.setText(entry.author);
            
            if (holder.bodyView != null)
            	holder.bodyView.setText(Html.fromHtml(entry.body)); //HTML 출력 가능하도록
      
            if (holder.regdateView != null) {
            	if (entry.regdate == null)
            		holder.regdateView.setText("");
            	else
            		holder.regdateView.setText(
            			DateUtil.stringFromDate("yyyy.MM.dd", entry.regdate, Locale.US));
            }
            
            if (holder.editBtn != null) {
            	holder.editBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(CmtAct.this, CmtModAct.class);
						intent.putExtra(App.INTENT_EXTRA_CMT_UID, Integer.valueOf(entry.uid));
						intent.putExtra("name", entry.author);
						intent.putExtra("homepage", entry.homepage);
						intent.putExtra("content", entry.body);
						CmtAct.this.startActivityForResult(intent, 2000);
					}
				});
            }
            
            if (holder.replyBtn != null)
            	holder.replyBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(CmtAct.this, CmtReplyAct.class);
						intent.putExtra(App.INTENT_EXTRA_NEWS_UID, Integer.valueOf(entry.news_uid));
						intent.putExtra(App.INTENT_EXTRA_CMT_UID, Integer.valueOf(entry.uid));
						CmtAct.this.startActivityForResult(intent, 3000);
					}
				});
            
            // 서브댓글 들여쓰기
            if (holder.wrapper != null && holder.bodyView != null) {
            	LinearLayout.LayoutParams l1 = (LinearLayout.LayoutParams)holder.wrapper.getLayoutParams();
            	LinearLayout.LayoutParams l2 = (LinearLayout.LayoutParams)holder.bodyView.getLayoutParams();
            	if (entry.pid > 0) { // 서브댓글
            		l1.leftMargin = (int)(20.0f * density);
            		l2.leftMargin = (int)(20.0f * density);
            		if (holder.replyBtn != null) 
            			holder.replyBtn.setVisibility(View.INVISIBLE);
            	} else {
            		l1.leftMargin = (int)(10.0f * density);
            		l2.leftMargin = (int)(10.0f * density);
            		if (holder.replyBtn != null) 
            			holder.replyBtn.setVisibility(View.VISIBLE);
            	}
            }
            
            if (holder.deleteBtn != null)
            	holder.deleteBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// 비번 입력창
						AlertDialog.Builder alert = new AlertDialog.Builder(CmtAct.this);
						alert.setTitle("알림");
						alert.setMessage("댓글을 작성하실 때 입력하신 비밀번호를 입력하여 주십시오.");
						
						LinearLayout layout = new LinearLayout(v.getContext());
						final EditText input = new EditText(v.getContext());
						input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
						input.setTransformationMethod(new PasswordTransformationMethod());
						LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
								LinearLayout.LayoutParams.FILL_PARENT,
								LinearLayout.LayoutParams.WRAP_CONTENT);
						params.setMargins(20, 0, 20, 0);
						layout.addView(input, params);
						alert.setView(layout);
						
						alert.setPositiveButton("삭제하기", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								final String password = input.getText().toString();
						    	progressDialog = ProgressDialog.show(
						        		CmtAct.this, "알림", "작성하신 댓글을 삭제하고 있습니다.", true, false);
						    	
						        new Thread() {
						            @Override
						            public void run() {
						            	Cmt cmt = new Cmt();
						            	cmt.uid = entry.uid;
						            	cmt.passwd = password;
						            	
						            	int code = DataLoader.deleteCmt(cmt); // 에러처리
						            	if (DebugFlag.isLogEnabled())
						            		Log.d(TAG, "postCmt code="+code);
						            	
						            	handler.sendEmptyMessage(CmtAct.HANDLER_MSG_FOR_DEL);
						            }
						        }.start();
							}
						});
						alert.setNegativeButton("취소", new DialogInterface.OnClickListener() {
							  public void onClick(DialogInterface dialog, int whichButton) {
							    // Canceled.
							  }
						});
						alert.show();
						
					}
				});
    		
    		return view;
        }
    }
    
	private class CmtHolder {
		public final TextView authorView;
		public final TextView bodyView;
		public final TextView regdateView;
		public final ImageButton replyBtn;
		public final ImageButton editBtn;
		public final ImageButton deleteBtn;
		public final RelativeLayout wrapper;
		
		public CmtHolder(View view) {
			authorView = (TextView)view.findViewById(R.id.cmt_row_author);
			regdateView = (TextView)view.findViewById(R.id.cmt_row_regdate);
			replyBtn = (ImageButton)view.findViewById(R.id.cmt_row_reply_btn);
			editBtn = (ImageButton)view.findViewById(R.id.cmt_row_mod_btn);
			deleteBtn = (ImageButton)view.findViewById(R.id.cmt_row_delete_btn);
			bodyView = (TextView)view.findViewById(R.id.cmt_row_text);
			wrapper = (RelativeLayout)view.findViewById(R.id.cmt_row_wrapper);
		}
	}
}
